"""
cdn.cdn_daemon

This should run as a separate process in parallel with the web server, triggering cdn.sync periodically.
"""
import os, signal, time, urllib2
import sys
sys.path.append('../../')
from jackson import settings1 as settings

def sync_daemon(func, per):
    """ A daemon responsible for periodically calling a CDN sync function.
    @author: ep
    """
    while True:
        urllib2.urlopen('http://127.0.0.1:' + str(settings.MY_PORT) + '/cdn/sync/' + func)
        time.sleep(per)

if __name__ == "__main__":
    # Daemons to start... (name, period)
    daemons = (('clean', settings.CLEAN_PERIOD),
               ('poke', settings.POKE_PERIOD),
               ('collect', settings.COLLECT_PERIOD)
               )
    
    # List to collect pid's of daemons so they can be killed
    pids = []
    
    for func, per in daemons:
        # Try to fork a daemon
        try:
            pid = os.fork()
            if pid == 0:
                # In the child, start the daemon
                sync_daemon(func, per)
            # In the parent, collect pid of daemon so we can clean up in event of an error
            pids.append(pid)
        except OSError, e:
            # In the event of an error, report it.
            print >>sys.stderr, "Failed to fork clean_content daemon: %d (%s)" % (e.errno, e.strerror)
            print "Killing forked daemons..."
            # And try to kill any daemons already forked
            for pid in pids:
                try:
                    os.kill(pid, signal.SIGTERM)
                except OSError, e:
                    print >>sys.stderr, "Failed to kill pid %d: %d (%d)" % (pid, e.errno, e.strerror)
            sys.exit(1)
    print pids

